import { Component, OnInit, Output, EventEmitter, Input, ViewChild } from '@angular/core';
import { UserDTO } from 'src/app/benshuo/model/user-dto';
import { OperationNotification, OperationType } from 'src/app/benshuo/util/data/operation-notification';
import { SchoolSelectComponent } from '../school-select/school-select.component';
import { NgForm } from '@angular/forms';
import { NzMessageService } from 'ng-zorro-antd';
import { SchoolService } from 'src/app/benshuo/services/school.service';
import { FormUtil } from 'src/app/benshuo/util/form/form-util';

@Component({
  selector: 'app-school-user',
  templateUrl: './school-user.component.html',
  styleUrls: ['./school-user.component.less'],
})
export class SchoolUserComponent implements OnInit {
  /**
   * 信息
   */
  detailItem: UserDTO = this.initFormData(null);

  /**
   * 详细窗口是否可见标志
   */
  // tslint:disable-next-line: variable-name
  _visible = false;

  /**
   * 调用后台API标志
   */
  loading = false;

  /**
   * 数据变化通知事件
   */
  @Output()
  notification = new EventEmitter<OperationNotification<UserDTO>>();

  /**
   * 学校
   */
  schooldto = '';

  /**
   * 详细窗口可见状态变化事件
   */
  @Output()
  visibleChange = new EventEmitter<boolean>();

  @Input()
  set visible(value: boolean) {
    if (value !== this._visible) {
      this._visible = value;
      this.visibleChange.emit(value);
    }
  }
  get visible(): boolean {
    return this._visible;
  }

  /**
   * 系统配置信息编辑组件
   */
  @ViewChild('eitorForm', null)
  editorForm: NgForm;

  /**
   * 系统配置信息编辑组件
   */
  @ViewChild('schoolSelect', null)
  school: SchoolSelectComponent;

  /**
   * 密码等级 默认0
   */
  level = 0;

  constructor(private msg: NzMessageService, private service: SchoolService) {}

  /**
   * 初始化表单数据
   *
   * @param item 要初始化的数据，为null表示新建
   */
  private initFormData(item?: UserDTO): UserDTO {
    return {
      id: item ? item.id : null,
      account: item ? item.account : null,
      name: item ? item.name : null,
      password: item ? item.password : null,
      enabled: item ? item.enabled : true,
      mail: item ? item.mail : null,
      school: {
        id: item ? (item.school ? item.school.id : null) : null,
      },
    };
  }

  ngOnInit() {
    this.detailItem = this.initFormData(null);
  }

  /**
   * 关闭数据详细窗口
   */
  onCancel() {
    this.visible = false;
  }

  /**
   * 验证表单，如果通过则保存
   *
   * @param firstTime 是否第1次调用，是则调用表单验证
   */
  validate(firstTime: boolean): void {
    if (firstTime) {
      FormUtil.validateForm(this.editorForm.form);
    }

    // 异步验证中
    if (this.editorForm.form.status === 'PENDING') {
      setTimeout(() => {
        this.validate(false);
      }, 100);
    } else {
      // 结束验证
      if (this.editorForm.form.valid) {
        this.save();
      }
    }
  }

  /**
   * 保存
   */
  save(): void {
    // 验证表单
    if (!FormUtil.validateForm(this.editorForm.form)) {
      return;
    }
    this.loading = true;
    this.detailItem.school.id = this.schooldto;
    console.log(this.detailItem);
    if (this.detailItem.id) {
      // tslint:disable-next-line: deprecation
      this.service.createUser(this.detailItem, this.detailItem.school.id).subscribe(
        data => this.afterItemSaved(data, OperationType.UPDATE),
        null,
        () => this.afterCallCompleted(),
      );
    } else {
      // tslint:disable-next-line: deprecation
      this.service.createUser(this.detailItem, this.detailItem.school.id).subscribe(
        data => this.afterItemSaved(data, OperationType.CREATE),
        null,
        () => this.afterCallCompleted(),
      );
    }
  }

  /**
   * 创建或修改数据, 父组件会调用该功能进行编辑操作
   *
   * @param item 要编辑的数据，如果为null则表示创建新的数据
   */
  edit(schoolId: string): void {
    this.detailItem = this.initFormData(null);
    this.detailItem.school.id = schoolId;
    this.visible = true;
    // 为了保证ViewChild可以取到值，先设置显示标志，再使用定时器来进行后续操作
    setTimeout(() => {
      FormUtil.resetForm(this.editorForm.form, this.detailItem);
      this.schooldto = this.detailItem.school.id;
    }, 100);
  }

  /**
   * 数据保存后的通用操作
   *
   * @param data 保存的数据
   * @param operation 操作类型
   */
  private afterItemSaved(data: UserDTO, operation: OperationType): void {
    this.loading = false;
    this.visible = false;
    this.notification.emit({
      operation,
      data,
    });
    this.msg.success('数据操作成功!');
  }

  /**
   * API调用完成后的操作
   */
  private afterCallCompleted(): void {
    this.loading = false;
  }
}
